<template>
  <el-dialog
    title="选择角色"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <!-- 列表穿梭框 -->
    <el-transfer
      :props="{
        key: 'id',
        label: 'name',
      }"
      filterable
      :titles="['未选中', '已选中']"
      v-model="selectedData"
      :data="tableData"
    ></el-transfer>

    <!-- 保存按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="update" :loading="loading">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
// api
import sysApi from "@/api/sysApi";

export default {
  name: "sysChooseRole",
  // 数据
  data() {
    return {
      // 用户ID
      selectedUserId: null,

      // 弹框显示状态
      dialogVisible: false,

      // 保存按钮加载状态
      loading: false,

      // 列表数据
      tableData: [],

      // 选中的数据
      selectedData: [],
    };
  },
  methods: {
    // 请求数据
    remoteData() {
      sysApi.sysRole
        .list()
        .then((roleListResult) => {
          sysApi.sysUser
            .userRoleIds(this.selectedUserId)
            .then((userRoleIdsResult) => {
              this.tableData = roleListResult.data;
              this.selectedData = userRoleIdsResult.data;
            })
            .catch((error) => {});
        })
        .catch((error) => {});
    },
    // 打开弹框
    open(row) {
      this.selectedUserId = row.id;
      this.remoteData();
      this.dialogVisible = true;
      this.loading = false;
    },
    // 更新用户角色列表
    update() {
      this.loading = true;
      sysApi.sysUser
        .updateUserRole(this.selectedData, this.selectedUserId)
        .then((res) => {
          this.$message.success({
            message: "关联成功",
            duration: 1000,
            onClose: () => {
              this.dialogVisible = false;
            },
          });
        })
        .catch((error) => { this.loading = false });
    },
  },
};
</script>